/**
* Created by tanyichao on 2017/3/20.
*/
<template>
    <div class="confirmOrder-index">
        <!--<x-header>确认订单</x-header>-->
        <scroller :height="-50+'px'" lock-x ref="scroller">
            <div class="content">
                <div class="head">
                   <span>
                       <img :src="orderConfirm.stStoreImg | urlFilterAddServer" alt="">
                       <span class="name">{{orderConfirm.stStoreName}}</span>
                   </span>
                    <span>
                        <span class="time">{{bktime}}</span>
                        <span class="status">{{ orderIsPackage }}</span>
                    </span>
                </div>
                <div class="orderList" v-if="orderConfirm.packages">
                    <div class="orderItem" v-for="package in orderConfirm.packages">
                        <span class="name">
                             <img :src="package.packageImg | urlFilterAddServer" alt="">
                             <span class="taste">
                                 <span>{{ package.packageName }}</span>
                                 <span class="tasteText" v-if="package.taste.length > 0">购买口味:{{ package.taste }}</span>
                             </span>
                        </span>
                        <span>
                            <span class="count">x{{ package.amount }}</span>
                            <span class="price">￥{{ package.price }}</span>
                        </span>
                    </div>

                </div>
                <div class="orderPrices" :class="{orderPrice:orderConfirm.strategyContent==''}">
                    <span :class="{display_blcok:orderConfirm.strategyContent!=''}">
                        <span class="order">订单：￥{{  orderConfirm.price}}</span>
                        <span class="preferential" v-if="orderConfirm.strStrategyId">{{ orderConfirm.strategyContent }}</span>
                    </span>
                    <span :class="{display_blcok2:orderConfirm.strategyContent!=''}" class="pay">待支付：￥{{ orderConfirm.strStrategyPrice }}</span>
                </div>
                <div class="chooseTime" v-if="diningModeType">
                    <span>*</span>
                    <datetime v-model="value2" 
                        format="HH:mm" 
                        @on-change="change" 
                        placeholder="请选择"
                        clear-text="选择就餐时间"
                        title="请选择就餐时间" 
                        confirm-text="确认" 
                        cancel-text="取消"
                        ></datetime>
                        <!-- :compute-hours-function="computeHoursFunction"  -->
                </div>
            </div>
        </scroller>
        <div class="confirmOrder_confirm">
            <div>待支付：￥{{ orderConfirm.strStrategyPrice }} ({{ leftTimerTime }})</div>
            <div @click="doConfirmOrder">微信支付</div>
        </div>
        <confirm v-model="orderConfirmShow" :title="orderConfirmShowText"
                 @on-cancel="onOrderCancel"
                 @on-confirm="onOrderConfirm">
        </confirm>
        <!--<confirm v-model="orderShow" :content="orderShowcontent" @on-cancel="ordercontentConfirm"-->
                 <!--@on-confirm="ordercontentConfirm">-->
        <!--</confirm>-->
        <alert v-model="orderShow" button-text="确定" @on-hide="ordercontentConfirm"><div style="color: red;">{{orderShowcontent}}</div><div>库存不足，请重新下单~</div></alert>
    </div>
</template>
<script>
    import {XHeader, Scroller, Datetime, Group, Confirm, Toast, Alert} from 'vux'

    import {getOrderInfoService, PostComfirmOrderService, openTimeService, clearCartService, WXPayService} from '../services/index'

    import {mapState, mapActions} from 'vuex'

    export default {
        components: {
            XHeader,
            Scroller,
            Datetime,
            Group,
            Confirm,
            Toast,
            Alert,
        },
        data(){
            return {
                value2: '',
                orderConfirm: {},
                orderId: '',
                orderConfirmShowText: '确认支付?',
                orderConfirmShow: false,
                leftTimerTime: '00分00秒',
                maxtime: "",
                mintime: "",
                bktime: "",
                stStoreId: '',
                orderShow:false,
                orderShowcontent:"",
                isrt:true,
                defaultTime : ""        
            }
        },
        watch : {
        },
        computed: {
            ...mapState({
                diningModeType: state => state.default.diningModeType,
                bookingTime: state => state.order.bookingTime,
                isPositionValue: state => state.vux.isPositionValue,
                isPositionValueText: state => state.vux.isPositionValueText,
            }),
            orderPriceAll(){
                let priceAll = 0;
                if (this.orderConfirm && this.orderConfirm.packages && this.orderConfirm.packages.length > 0) {
                    this.orderConfirm.packages.forEach((item, index) => {
                        priceAll += item.price * item.amount;
                    })
                }
                return priceAll;
            },
            orderIsPackage(){
                let isPackage = '';
                switch (this.orderConfirm.isPackage) {
                    case '0' :
                        isPackage = '堂食';
                        break;
                    case '1' :
                        isPackage = '打包';
                        break;
                    case '2' :
                        isPackage = '净菜包';
                        break;
                }
                return isPackage; 
            },
            payPriceNum(){
                let payPrice = 0;
                if(this.orderConfirm.strStrategyId){
                    payPrice = this.orderConfirm.price - this.orderConfirm.reduce;
                }else {
                    payPrice = this.orderConfirm.price;
                }
                return payPrice;
            }
        },
        activated(){
            if (this.orderId != '' || this.orderId != this.$route.query.orderId) {
                this.orderId = this.$route.query.orderId;
                this.getOrderInfo();
            }
            if (this.stStoreId != '' || this.stStoreId != this.$route.query.stStoreId) {
                this.stStoreId = this.$route.query.stStoreId;
            }

        },
        mounted(){
            
        },
        deactivated(){
            const hideMask = document.getElementsByClassName('dp-mask')[0];
            if (hideMask) {
                hideMask.click()
            }
            this.$destroy(true)
        },
        methods: {
            _defaultTime(isLunch){
                if(isLunch == "0"){
                    this.value2 = "12:30"
                }else if(isLunch == "1"){
                    this.value2 = "17:30"
                }
            },
            computeHoursFunction(date, isToday, generateRange){
                const that = this;
                const isLunch = that.orderConfirm.isLunch;
                if(isLunch == "0"){
                    return generateRange(10, 14)
                }else if(isLunch == "1"){
                    return generateRange(17, 19)
                }
            },
            ...mapActions([
                'updateOrderId',
                'updateIsPositionValue',
                'updateIsPositionValueText',
                'updateStoreId'
            ]),
            change(){

            },
            openTime(param){
                openTimeService().save({stStoreId: param.stStoreId}).then((res) => {
                    const body = res.body;
                    if (body && body.code == 200) {
                        let open_Time = body.data;
                        this.maxtime = ~~open_Time.endTime.split(":")[0]
                        this.mintime = ~~open_Time.startTime.split(":")[0]
                    }
                })
            },
            threeday(){
                let _date = new Date();
                let _year = '0' + _date.getFullYear();
                let _month = '0' + ( _date.getMonth() + 1 );
                let _day = '0' + (_date.getDate());

                _year = _year.substr(_year.length - 4);
                _month = _month.substr(_month.length - 2);
                _day = _day.substr(_day.length - 2);

                return ( _year + '-' + _month + '-' + _day );
            },
            getOrderInfo(){
                getOrderInfoService().save({orderId: this.orderId}).then((res) => {
                    const body = res.body;

                if (body && body.code == 200) {
                    this.orderConfirm = body.data;
                    this.bktime = body.data.bookingTime.split(" ")[0] || body.data.createTime.split(" ")[0];
                    window.leftTimer = setInterval(() => {
                            this.leftTimer(this.orderConfirm.createTime)
                    },1000);
                    this.$refs.scroller.reset();
                    this.openTime(body.data);

                    this._defaultTime(this.orderConfirm.isLunch)

                }
            })
            },
            doConfirmOrder(){
                this.orderConfirmShow = true;
                this.updateIsPositionValue(false);
            },
            postConfirmOrder(){
                let okparam = "";
                if (this.diningModeType) {
                    if (this.value2 == "") {
                        this.updateIsPositionValueText("请选择就餐时间");
                        this.updateIsPositionValue(true);
                        return;
                    } else if (this.bookingTime == this.threeday()) {
                        if (this.value2) {
                            let alltime = this.value2.split(":");
                            alltime = alltime[0] * 60 * 60 * 1000 + alltime[1] * 60 * 1000;
                            let _date = new Date();
                            let curtime = _date.getHours() * 60 * 60 * 1000 + _date.getMinutes() * 60 * 1000;
                            if (alltime < curtime) {
                                this.updateIsPositionValue(true);
                                this.updateIsPositionValueText("不在当前时间内，请选择合适的时间");
                                return;
                            }

                        }
                    }
                    let dinnerTime1 = this.orderConfirm.bookingTime.split(" ")[0] + " " + this.value2 + ":" + "00";
                    okparam = {
                        orderId: this.orderId,
                        dinnerTime: dinnerTime1,
                    }
                } else {
                    okparam = {
                        orderId: this.orderId,
                    }
                }
                WXPayService().save(okparam).then((param) => {
                    let res = param.body;
                    if (res && res.code == 301) {

                        this.$router.push({
                            name: 'orderInfo',
                            query: {
                                orderId: this.orderId
                            }
                        });
                        return;
                    }
                    WeixinJSBridge.invoke(
                        'getBrandWCPayRequest', {
                            "appId":res.data.appId,     //公众号名称，由商户传入
                            "timeStamp":res.data.timeStamp,         //时间戳，自1970年以来的秒数
                            "nonceStr":res.data.nonceStr, //随机串
                            "package":res.data.package,
                            "signType":res.data.signType, //微信签名方式：
                            "paySign": res.data.paySign //微信签名
                        },
                        (ress)=>{
                            if(ress.err_msg == "get_brand_wcpay_request:ok" ) {
                                clearCartService().save({storeId: this.stStoreId}).then(res => {
                                    const body = res.body;
                                    if (body && body.code == 200) {
                                        if (this.stStoreId != "") {
                                            this.updateStoreId(this.stStoreId);
                                            window.localStorage.setItem('stStoreId', this.stStoreId);
                                        }
                                        this.$router.replace({
                                            name: 'orderInfo',
                                            query: {
                                                orderId: this.orderId
                                            }
                                        })
                                    }
                                })
                            }
                        }
                    );
                })
//                PostComfirmOrderService().save(okparam).then((res) => {
//                    const body = res.body;
//                    if (body && body.code == 200) {
//                        this.updateOrderId('');
//                        clearCartService().save({storeId: this.stStoreId}).then(res => {
//                            const body = res.body;
//                            if (body && body.code == 200) {
//                                if (this.stStoreId != "") {
//                                    this.updateStoreId(this.stStoreId);
//                                    window.localStorage.setItem('stStoreId', this.stStoreId);
//                                }
//                                this.$router.replace({
//                                    name: 'orderInfo',
//                                    query: {
//                                        orderId: this.orderId
//                                    }
//                                })
//                            }
//                        })
//                    }else if(body && body.code == 555){
//                        this.orderShow = true;
//                        this.orderShowcontent = body.msg;
//                    }else if(body && body.code == 556){
//                        this.orderShow = true;
//                        this.orderShowcontent = body.msg;
//                    }
//                })
            },
            ordercontentConfirm(){
                this.$router.back();
            },
            onOrderCancel(){
                this.orderConfirmShow = false;
            },
            onOrderConfirm(){
                this.isorder = true;
                this.postConfirmOrder();
            },
            goOrderInfo(){
                this.$router.push({
                    name: 'orderInfo',
                    query: {
                        orderId: this.orderId
                    }
                })
            },
            leftTimer(time){
                let leftTime = ((new Date(time.replace(/-/g, '/')) - new Date())); //计算剩余的毫秒数
//                let days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
//                let hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //计算剩余的小时
                let minutes = String(14 + parseInt(leftTime / 1000 / 60 % 60, 10));//计算剩余的分钟
                let seconds = String(60 + parseInt(leftTime / 1000 % 60, 10));//计算剩余的秒数
                if (minutes < 0) {
                    this.leftTimerTime = '00分00秒';
                    window.clearInterval(window.leftTimer);
                    this.$router.push({
                        name: 'orderInfo',
                        query: {
                            orderId: this.orderId
                        }
                    });
                } else {
//                    days = this.checkTime(days);
//                    hours = this.checkTime(hours);
//                    minutes = this.checkTime(minutes);
//                    seconds = this.checkTime(seconds);
                    this.leftTimerTime = minutes + "分" + seconds + "秒";
                }
            },
            checkTime(i){
                if (i < 10) {
                    i = "0" + i;
                }
                return i;
            }
        },
        updated(){
            setTimeout(() => {
                this.$refs.scroller.reset();
        }, 500)
        }

    }
</script>
<style lang="less" rel="stylesheet/less">
    .confirmOrder-index {
        width: 100%;
        height: auto;
        .weui-cell {
            border: 1px solid #fff;
        }
        .content {
            display: flex;
            flex-flow: column nowrap;
            justify-content: flex-start;
            position: relative;

            .head {
                display: flex;
                flex-flow: row nowrap;
                font-size: 0.6rem;
                background-color: #fff;
                justify-content: center;
                align-items: center;
                padding: 0.5rem 1rem;

                > span {
                    display: flex;
                    flex-flow: row nowrap;
                    align-items: center;
                }
                > span:nth-child(1) {
                    width: 60%;
                    justify-content: flex-start;
                    .name {
                        margin-left: 0.25rem;
                    }
                }
                > span:nth-child(2) {
                    width: 40%;
                    justify-content: space-between;
                    .time {
                        color: #999;
                    }
                    .status {
                        color: #fa5a4c;
                    }
                }
                img {
                    width: 1rem;
                    height: 1rem;
                }
            }
            .orderList {
                display: flex;
                flex-flow: column nowrap;
                justify-content: center;
                padding: 0.5rem 1rem;
                background-color: #eee;
                .orderItem {
                    display: flex;
                    flex-flow: row nowrap;
                    justify-content: flex-start;
                    padding: 0.25rem 0;

                    img {
                        width: 2rem;
                        height: 2rem;
                    }
                    >span {
                        display: flex;
                        flex-flow: row nowrap;
                        font-size: 0.75rem;
                        width: 80%;
                    }
                    > span:nth-child(1) {
                        width: 70%;
                        justify-content: flex-start;
                        align-items: center;
                    }
                    > span:nth-child(2) {
                        width: 30%;
                        justify-content: space-between;
                        align-items: center;
                    }
                    .count {
                        color: #d1d1d1;
                    }
                    .taste{
                        display: flex;
                        flex-direction: column;
                        flex-wrap: nowrap;
                        margin-left: 0.5rem;
                    }
                    .tasteText{
                        font-size: 0.5rem;
                        color: #999;
                    }
                }
            }
            .orderPrices {
                font-size: 0.7rem;
                flex-flow: row nowrap;
                justify-content: space-between;
                background-color: #fff;
                align-items: center;
                padding: 0 1rem;
                height: auto;
                .order {
                    color: #999;
                }
                .preferential {
                    margin-left: 0.5rem;
                    color: #999;
                }
            }
            .orderPrice {
                font-size: 0.7rem;
                display: flex;
                flex-flow: row nowrap;
                justify-content: space-between;
                background-color: #fff;
                align-items: center;
                padding: 0 1rem;
                height: 2rem;

                .order {
                    color: #999;
                }
                .preferential {
                    margin-left: 0.5rem;
                    color: #999;
                }
            }
            .chooseTime {
                background-color: #fff;
                margin-top: 0.5rem;
                position: relative;
                padding-left: 1rem;
                font-size: 0.75rem;
                > span {
                    position: absolute;
                    top: 50%;
                    transform: translateY(-45%);
                    color: red;
                }
                .weui-cell:before {
                    border: none !important;
                }
            }

        }
    }

    .confirmOrder_confirm {
        position: absolute;
        bottom: 0px;
        right: 0px;
        left: 0px;
        height: 2.5rem;
        font-size: 0px;
        background-color: #fff;

        div {
            display: inline-block;
            font-size: 0.8rem;
            line-height: 300%;
        }
        div:nth-child(1) {
            width: 70%;
            height: 100%;
            background-color: #252525;
            padding-left: 15px;
            color: #fff;
        }
        div:nth-child(2) {
            width: 30%;
            height: 100%;
            text-align: center;
            background-color: #fc832e;
            color: #fff;
        }
    }

    .dp-left {
        color: #929292 !important;
    }

    .dp-center {
        color: #333 !important;
    }

    .dp-right {
        color: #e84139 !important;
    }
    .display_blcok{
        display: block;
        height: 1.2rem;
        line-height: 1.2rem;
    }
    .display_blcok2{
        display: block;
        height: 1.2rem;
        line-height: 1.2rem;
        text-align: right;
    }
</style>
